<template>
  <div class="participation-form">
    <h2>{{ isEdit ? '编辑活动参与记录' : '添加活动参与记录' }}</h2>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form-container"
    >
        <el-form-item label="用户" prop="userId">
        <el-select 
          v-model="form.userId" 
          placeholder="请选择用户" 
          filterable
          :disabled="isEdit || !canSelectUser">
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.username"
            :value="user.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动" prop="activityId">
        <el-select v-model="form.activityId" placeholder="请选择活动" filterable
                  :disabled="isEdit">
          <el-option
            v-for="activity in activityOptions"
            :key="activity.id"
            :label="activity.title"
            :value="activity.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
  
      
      <!-- ✅ 签到时间相关部分已移除 -->

      <el-form-item label="投票选项" prop="voteOption">
        <el-select v-model="form.voteOption" placeholder="请选择投票选项">
          <el-option
            v-for="(option, index) in voteOptions"
            :key="index"
            :label="option"
            :value="option"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="活动反馈" prop="feedback">
        <el-input
          v-model="form.feedback"
          type="textarea"
          :rows="4"
          placeholder="请输入活动反馈"
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getParticipationDetail, addParticipation, updateParticipation } from '@/api/activityParticipation'
import { getClubMembersByUserId } from '@/api/clubMember'
import { getActivitiesByClubId, getActivityList } from '@/api/activity'
import { getUserList } from '@/api/user'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref(null)
const activityOptions = ref([])
const userOptions = ref([])

const voteOptions = [
  '非常满意', '满意', '一般', '不满意', '非常不满意', '支持', '反对', '中立', '弃权'
]

const currentUser = computed(() => userStore.userInfo)
const canSelectUser = computed(() => currentUser.value.role === 'admin' || currentUser.value.role === 'club_leader')
const isEdit = computed(() => route.params.id !== undefined)

const form = reactive({
  activityId: null,
  userId: null,
  voteOption: '',
  feedback: ''
})

const rules = reactive({
  activityId: [{ required: true, message: '请选择活动', trigger: 'change' }],
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  voteOption: [{ required: false, message: '请选择投票选项', trigger: 'change' }],
  feedback: [{ required: false, message: '请输入活动反馈', trigger: 'blur' }]
})

// ✅ 核心逻辑：根据用户加载活动
const loadActivitiesByUser = async (userId) => {
  if (!userId) {
    activityOptions.value = []
    return
  }
  try {
    // 查询该用户所在社团
    const resClubs = await getClubMembersByUserId(userId)
    if (resClubs.code === 200 && Array.isArray(resClubs.data)) {
      const approvedClubs = resClubs.data.filter(item => item.status === 'approved')
      const allActivities = []
      // 遍历社团，查活动
      for (const club of approvedClubs) {
        const resActivities = await getActivitiesByClubId(club.clubId)
        if (resActivities.code === 200 && Array.isArray(resActivities.data)) {
          allActivities.push(...resActivities.data)
        }
      }
      activityOptions.value = allActivities
    } else {
      activityOptions.value = []
    }
  } catch (error) {
    console.error('获取活动列表出错:', error)
    ElMessage.error('获取活动列表失败')
    activityOptions.value = []
  }
}

// ✅ 加载用户列表
const loadUsers = async () => {
  try {
    const res = await getUserList({ pageSize: 1000 })
    if (res.code === 200 && res.data?.list) {
      userOptions.value = res.data.list
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// ✅ 获取已有记录详情
// ✅ 获取已有记录详情
const getParticipationInfo = async (id) => {
  try {
    const res = await getParticipationDetail(id)
    if (res.code === 200 && res.data) {
      form.userId = res.data.userId
      form.voteOption = res.data.voteOption
      form.feedback = res.data.feedback
      
      // ⚠️ 先加载用户对应的活动
      await loadActivitiesByUser(res.data.userId)

      // ✅ 再设置活动 ID（保证下拉框有选项时再绑定）
      form.activityId = res.data.activityId
    } else {
      ElMessage.error(res.message || '获取参与记录信息失败')
      goBack()
    }
  } catch (error) {
    console.error('获取参与记录详情出错:', error)
    ElMessage.error('获取参与记录信息失败')
    goBack()
  }
}


// ✅ 监听 userId 改变时动态加载活动
watch(() => form.userId, (newUserId) => {
  if (newUserId) {
    loadActivitiesByUser(newUserId)
    form.activityId = null // 清空旧选择
  } else {
    activityOptions.value = []
  }
})

// ✅ 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    const res = isEdit.value
      ? await updateParticipation(route.params.id, form)
      : await addParticipation(form)

    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      goBack()
    } else {
      ElMessage.error(res.message || (isEdit.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单数据不完整或格式不正确')
  }
}

const goBack = () => router.push('/activity-participations')

// ✅ 初始化逻辑
onMounted(async () => {
  await loadUsers()
  if (isEdit.value && route.params.id) {
    await getParticipationInfo(route.params.id)
  } else {
    // 默认当前用户
    form.userId = currentUser.value.id
    await loadActivitiesByUser(form.userId)
  }
})

</script>


<style scoped>
.participation-form {
  padding: 20px;
}

.form-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 